package com.zzy.rpc;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.zzy.commons.IOUtils;

public class ClientBAK {
	
	private static Log LOG = LogFactory.getLog(ClientBAK.class);
	
	private String host;
	private int port;
	private Socket socket;
	private DataInputStream				in;
	private DataOutputStream			out;
	
	public ClientBAK(String host, int port) {
		this.host = host;
		this.port = port;
		init();
	}
	
	private void init() {
		try {
			socket = new Socket(host, port);
			this.in = new DataInputStream(socket.getInputStream());
			this.out = new DataOutputStream(socket.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void invoke(Invocation invocation)  {
		try {
			byte[] sendBuffer = IOUtils.toByte(invocation);
			out.write(sendBuffer);
			LOG.info("1.client sendBuffer length: " + sendBuffer.length);
			
			int length = in.readInt();
			byte[] receiveBuffer = new byte[length];
			int position = 0;
			byte[] buffer = new byte[length];
			int hasRead = 0;
			
			while((position = in.read(buffer, 0, buffer.length)) != -1) {
				hasRead += position;
				if(hasRead == length) {
					break;
				}
			}
			LOG.info("4.client receiveBuffer length: " + length);
			byte[] newBuffer = new byte[length - 4];
			System.arraycopy(buffer, 4, newBuffer, 0, newBuffer.length);
			Invocation invoc = (Invocation) IOUtils.toObject(newBuffer);
			invocation.setResult(invoc.getResult());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void setHost(String host) {
		this.host = host;
	}
	
	public String getHost() {
		return host;
	}
	
	public void setPort(int port) {
		this.port = port;
	}
	
	public int getPort() {
		return port;
	}
	
}
